package com.xxy.utils;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;

import com.xxy.properties.TencentCosProperties;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.util.UUID;

@Component
@RequiredArgsConstructor
public class TencentCosUtil {

    private final TencentCosProperties cosProperties;

    private COSClient cosClient;

    private COSClient getClient() {
        if (cosClient == null) {
            COSCredentials credentials = new BasicCOSCredentials(cosProperties.getSecretId(), cosProperties.getSecretKey());
            ClientConfig clientConfig = new ClientConfig(new Region(cosProperties.getRegion()));
            cosClient = new COSClient(credentials, clientConfig);
        }
        return cosClient;
    }

    public String upload(MultipartFile file) {
        try {
            // 生成安全的文件名
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = UUID.randomUUID().toString() + suffix;

            // 临时保存文件
            File tempFile = File.createTempFile("cos-", suffix);
            try (FileOutputStream fos = new FileOutputStream(tempFile)) {
                fos.write(file.getBytes());
            }

            // 构造上传请求
            PutObjectRequest request = new PutObjectRequest(
                    cosProperties.getBucket(), fileName, tempFile
            );
            PutObjectResult result = getClient().putObject(request);

            // 删除临时文件
            tempFile.delete();

            // 拼接并返回可访问 URL
            return cosProperties.getPrefix() + "/" + fileName;

        } catch (Exception e) {
            throw new RuntimeException("上传图片失败：" + e.getMessage(), e);
        }
    }
}
